import { createRouter, createWebHistory } from 'vue-router';

// 所有路由的组件引用
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('./views/Login.vue')
  },
  {
    path: '/',
    name: 'Home',
    component: () => import('./views/Home.vue'),
    redirect: '/public-activities',
    children: [
      // 动态添加的子路由将会放在这里
    ]
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 页面需要认证
  const publicPages = ['/login'];
  const authRequired = !publicPages.includes(to.path);
  
  // 检查用户是否已登录（从localStorage获取状态）
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true';
  const userRole = localStorage.getItem('userRole') || 'student';
  
  // 存储当前状态到localStorage
  if (!isAuthenticated && authRequired) {
    // 未登录用户重定向到登录页
    next('/login');
  } else if (to.path === '/' && isAuthenticated) {
    // 首页根据用户角色自动跳转到相应页面
    if (userRole === 'admin') {
      next('/activity-management');
    } else {
      next('/public-activities');
    }
  } else if (to.path === '/activity-management' && userRole !== 'admin') {
    // 非管理员访问活动管理页时提示无权限并返回首页
    alert('您没有权限访问该页面！');
    next('/');
  } else {
    // 否则继续导航
    next();
  }
});

export default router;